package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 工单查询API
 */

public class apiGetWOList implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetWOList.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        JSONObject signJson = signUtil.CheckSign(JSONObject.parseObject(callJson, Feature.OrderedField));
        //log.info("[签名验证结果]:");
        //log.info(signJson);
        //if (signJson != null && 1==2) {
        if (1==2) {
            return signJson.toString();
        } else {
            try {
                //解析Json
                JSONObject inJson = JSONObject.parseObject(callJson, Feature.OrderedField);

                //获取查询参数
                String c_user_id = inJson.getString("c_user_id");
                String c_user_type = inJson.getString("c_user_type");
                /** 查询类型--
                 * 待处理工单：user
                 * 超时：timeout
                 * 已处理工单：OPENHIS
                 * 已办结工单:CLOSEHIS
                 * 所有工单:involve
                 * 待流转工单:transfer
                 */
                String s_query_type = inJson.getJSONObject("data").getString("s_query_type");
                String s_query_info = inJson.getJSONObject("data").getString("s_query_info"); // 模糊查询项
                String s_workorder_id = inJson.getJSONObject("data").getString("s_workorder_id");// 输入的工单ID
                String s_customer_name = inJson.getJSONObject("data").getString("s_customer_name"); // 客户姓名
                String s_customer_mobile = inJson.getJSONObject("data").getString("s_customer_mobile");// 手机
                String s_workorder_status = inJson.getJSONObject("data").getString("s_workorder_status"); // 工单状态
                String s_timedimension = inJson.getJSONObject("data").getString("s_timedimension"); // 工单筛选时间 近一周oneweek	近一个月onemonth 近三个月threemonth 全部all
                String wo_s_deal = inJson.getJSONObject("data").getString("wo_s_deal"); // 工单查询类型 1.所有工单 2.待办工单 5.我的关注工单 6.已办结工单 7.我的归档工单 8.已结案工单 9.已关闭工单
                String s_task_createdate_s = inJson.getJSONObject("data").getString("s_task_createdate_s"); // 工单创建开始时间
                String s_task_createdate_e = inJson.getJSONObject("data").getString("s_task_createdate_e"); // 工单创建结束时间
                String s_task_enddata_s = inJson.getJSONObject("data").getString("s_task_enddata_s"); // 工单结案开始时间
                String s_task_enddata_e = inJson.getJSONObject("data").getString("s_task_enddata_e"); // 工单结案结束时间
                String s_frameid = inJson.getJSONObject("data").getString("s_frameid"); // 工单名称id
                String s_nodeid = inJson.getJSONObject("data").getString("s_nodeid"); // 工单步骤id
                String s_customername1 = inJson.getJSONObject("data").getString("s_customername1"); // 客户名称
                String s_tel1 = inJson.getJSONObject("data").getString("s_tel1"); // 电话
                String s_business_number = inJson.getJSONObject("data").getString("s_business_number"); // 物业号

                log.debug("请求参数-操作人信息-c_user_id:" + c_user_id);
                log.debug("请求参数-查询条件-s_query_type:" + s_query_type  + " s_query_info:" + s_query_info + " s_workorder_id:" + s_workorder_id + " s_customer_name:" + s_customer_name + " s_customer_mobile:" + s_customer_mobile + " s_workorder_status:" + s_workorder_status+ " s_timedimension:" + s_timedimension+ " s_business_number:" + s_business_number);

                // 查询判断当前这个操作人是客户还是员工
                // 客户信息
                String Customer_Guid = null;
                String Loginname = null;

                // 员工信息
                String Rolegroup_Id = null;
                String Staff_Id = null;
                String rolegrouptype = null;
                String roleStr=null;
                List selectResult = eliteBean.chaxun_sql("Select DEFAULTROLEGROUP as Rolegroup_Id, R1.Staff_Id, R1.Staffname " +
                        "  From Staff R1" +
                        " Where R1.Workstatus = 'ONLINE'" +
                        "   And R1.Staff_Id = '" + c_user_id + "' limit 1", "dataSource");
                log.debug("查询出的话务员表长度："+selectResult.size());
                if (selectResult.size() <= 0) {
                    result.put("code", 1007);
                    result.put("msg", "当前操作人非法！");
                    return result;
                } else {
                    Map selectResultm = selectResult.get(0);
                    Rolegroup_Id = selectResultm.get("Rolegroup_Id");
                    Staff_Id = selectResultm.get("Staff_Id");
                    String Rolegroupdescription = selectResultm.get("Rolegroupdescription");
                    String Staffname = selectResultm.get("Staffname");
                    log.debug("当前操作员工信息-Rolegroup_Id:" + Rolegroup_Id + " Staff_Id:" + Staff_Id + " Staffname:" + Staffname);
                    c_user_type = "staff";
                    List rolelist=eliteBean.chaxun_sql("select group_concat(role_id) roleStr from staffrole where staff_id='"+Staff_Id+"'", "dataSource");
                    Map rolemap=rolelist.get(0);
                    roleStr=rolemap.get("roleStr");
                }
                String q_WhereSQL="";



                /**
                 * 各类型工单SQL条件拼接
                 */

                //待处理工单
                if (s_query_type == "user"){
                    q_WhereSQL = q_WhereSQL +" and Obj.objectivestatus='OPEN' And  Eta.HandleBy_ID='"+Staff_Id+"'";
                }
                //超时工单
                else if(s_query_type == "timeout"){
                    q_WhereSQL = q_WhereSQL +" and Obj.objectivestatus='OPEN'  and  Eta.HandleBy_ID='"+Staff_Id+"' and Eta.EXPECTENDTIME<now()";
                }
                //已处理工单
                else if(s_query_type == "OPENHIS"){
                    q_WhereSQL = q_WhereSQL +" and Obj.objectivestatus='OPEN' and Obj.HandleBy_ID!='"+Staff_Id+"' and ifnull(eta. objectivetype_id,'')!='' AND WS.OLDHANDLEBY_ID='"+Staff_Id+"'";
                }
                //已办结工单
                else if(s_query_type == "CLOSEHIS"){
                    q_WhereSQL = q_WhereSQL +" AND Obj.objectivestatus='CLOSE'  AND WS.OLDHANDLEBY_ID='"+Staff_Id+"'"
                }
                //所有工单-自己
                else if(s_query_type == "involve" && Rolegroup_Id != "L2SNS4"){
                    q_WhereSQL = q_WhereSQL +" And  (Eta.HandleBy_ID='"+Staff_Id+"' or WS.OLDHANDLEBY_ID='"+Staff_Id+"')"
                }
                else if(s_query_type == "involve" && Rolegroup_Id == "L2SNS4"){

                }
                //待流转工单
                else if(s_query_type == "transfer"){
                    q_WhereSQL = q_WhereSQL + " and w1.HANDLEBY_ID!='"+Staff_Id+"' and wn.HANDLEBY_ID='"+Staff_Id+"'  and Obj.map_id!='KL3YUM' And Obj.objectivestatus='OPEN' and Obj.objective_guid not in ( select objective_guid from objective o left join workorderstep3 w1 on o.OBJECTIVE_GUID=w1.WORKORDER_GUID where w1.OLDHANDLEBY_ID='"+Staff_Id+"' )"
                }




                /**
                 * 筛选条件条件拼接
                 */

                //查询条件
                //s_timedimension 工单筛选时间 近一周oneweek	近一个月onemonth 近三个月threemonth 全部all
                if(s_timedimension=='oneweek'){
                    q_WhereSQL = q_WhereSQL + " and DATE_FORMAT(Obj.createddate,'%Y-%m-%d %H:%i:%s')>DATE_FORMAT(DATE_SUB(now(),INTERVAL 7 day),'%Y-%m-%d %H:%i:%s')";
                }else if(s_timedimension=='onemonth'){
                    q_WhereSQL = q_WhereSQL + " and DATE_FORMAT(Obj.createddate,'%Y-%m-%d %H:%i:%s')>DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 MONTH),'%Y-%m-%d %H:%i:%s')";
                }else if(s_timedimension=='threemonth'){
                    q_WhereSQL = q_WhereSQL + " and DATE_FORMAT(Obj.createddate,'%Y-%m-%d %H:%i:%s')>DATE_FORMAT(DATE_SUB(now(),INTERVAL 3 MONTH),'%Y-%m-%d %H:%i:%s')";
                }else if(s_timedimension=='all'){

                }
                //工单编号
                if (s_workorder_id!=''&&s_workorder_id!=null) {
                    q_WhereSQL = q_WhereSQL + " And Obj.Workorderid = '" + s_workorder_id + "'";
                }
                //客户姓名
                if (s_customer_name!=''&&s_customer_name!=null) {
                    q_WhereSQL = q_WhereSQL + " And Cus.Customername like '" +"%" + s_customer_name +"%"+ "'";
                }
                //手机号码
                if (s_customer_mobile!=''&&s_customer_mobile!=null) {
                    q_WhereSQL = q_WhereSQL + " And (Cus.tel_1 = '" +"%"+ s_customer_mobile +"%"+ "' or cus.tel_2 like '"+"%"+s_customer_mobile+"%"+"' or cus.mobile like '"+"%"+s_customer_mobile+"%"+"' )";
                }
                //工单状态
                if (s_workorder_status!=''&&s_workorder_status!=null) {
                    q_WhereSQL = q_WhereSQL + " And so.objectivestatus = '" + s_workorder_status + "'";
                }
                //物业号
                if (s_business_number!=''&&s_business_number!=null) {
                    q_WhereSQL = q_WhereSQL + " And Obj.businessnumber = '" + s_business_number + "'";
                }



                if(s_task_createdate_s!=""){
                    q_WhereSQL=q_WhereSQL+" And obj.createddate>='"+s_task_createdate_s+"'";
                }
                if(s_task_createdate_e!=""){
                    q_WhereSQL=q_WhereSQL+" And obj.createddate<='"+s_task_createdate_e+"'";
                }
                if(s_task_enddata_s!=""){
                    q_WhereSQL=q_WhereSQL+" And obj.ModifiedDate>='"+s_task_enddata_s+"'";
                }
                if(s_task_enddata_e!=""){
                    q_WhereSQL=q_WhereSQL+" And obj.ModifiedDate>='"+s_task_enddata_e+"'";
                }
                if(s_frameid!=""){
                    q_WhereSQL=q_WhereSQL+"  And obj.map_id='"+s_frameid+"'";
                }
                if(s_nodeid!=""){
                    q_WhereSQL=q_WhereSQL+"  And obj.curstep_id_map='"+s_nodeid+"'";
                }

                q_WhereSQL = q_WhereSQL + " order by DATE_FORMAT(Obj.MODIFIEDDATE,'%Y-%m-%d %H:%i:%s') desc limit 300";
                log.debug("控制查询条件完成SQL:" + q_WhereSQL);

                String queryWorkOrderSQL = "Select Distinct Obj.Workorderid As workorder_id,\n" +
                        "                Obj.Objective_Guid As objective_guid,\n" +
                        "                Eta.Elitetask_Guid As elitetask_guid,\n" +
                        "                fm.mapname As map_name,\n" +
                        "                Nm.Nodemapname As node_name,\n" +
                        "                Cus.Customername As Customername,\n" +
                        "                Cus.Mobile As mobile,\n" +
                        "                DATE_FORMAT(eta.expectstarttime,'%Y-%m-%d %H:%i:%s')  As expectstarttime,\n" +
                        "                DATE_FORMAT(eta.expectendtime,'%Y-%m-%d %H:%i:%s') As expectendtime,\n" +
                        "                Priy.Prioritydescription As Prioritydescription,\n" +
                        "                R1.Rolegroupdescription As Rolegroupdescription,\n" +
                        "                S1.Staffname As Staffname,\n" +
                        "                Obj.Comments As comments,case  when  Obj.objectivestatus='OPEN' then '等待处理' when  Obj.objectivestatus='CLOSE' then '成功结案'  when  Obj.objectivestatus='FAIL' then '失败结案'  end as objectivestatus,\n" +
                        "                DATE_FORMAT(Obj.MODIFIEDDATE,'%Y-%m-%d %H:%i:%s') as MODIFIEDDATE,\n" +
                        "                DATE_FORMAT(Obj.CREATEDDATE,'%Y-%m-%d %H:%i:%s') as CREATEDDATE,\n" +
                        "                so.objectivestatusdescription as objectivestatusdescription,\n" +
                        "                case  when Obj.objectivestatus='CLOSE' then '成功结案' when  Obj.objectivestatus='FAIL' then '失败结案'  end as workorderstate,\n" +
                        "                obj.map_id as map_id,\n" +
                        "                tw.tenant as tenant,\n" +
                        "                tw.tenant_mobile as tenant_mobile,\n" +
                        "                tw.acceptor as acceptor,\n" +
                        "                tw.writedate as writedate,\n" +
                        "                eta.comments as tcomments,\n" +
                        "                obj.handlerole_id as handlerole_id,\n" +
                        "Concat('<div data-type=\"LABEL\" class=\"CtlLabel-container\" style=\"width: 1.7rem; height: 0.5rem; font-size: 12px; color: rgb(255, 255, 255); background-color: ',case when obj.objectivestatus='OPEN' THEN '#6397e4' when obj.objectivestatus='CLOSE' then '#29da81' else 'red' end,'; position: relative; display: flex;\"><div class=\"CtlLabel-input\" style=\"justify-content: center;overflow: hidden;\"><span class=\"CtlLabel-input-nowrap\">',so.objectivestatusdescription,'</span></div></div>') as objectivestatusdescription," +
                        "                case when tw.print_flag='1' then '已打印' else '未打印' end as print_flag,\n" +
                        "                tw.stalls_code,\n" +
                        "                obj.objectivestatus objectivestatusid,\n" +
                        "                role.ROLENAME,obj.businessnumber,wo_expand.applicant as createstaff\n" +

                        "  From Objective Obj\n" +
                        "  LEFT JOIN WORKORDERSTEP3 WS ON Obj.objective_guid=wS.workorder_guid\n" +
                        "  Left Join Elitetask Eta\n" +
                        "    On Eta.Objective_Guid = Obj.Objective_Guid\n" +
                        "  Left Join hjx_workdateinfo wo_expand\n" +
                        "    On wo_expand.Objective_Guid = Obj.Objective_Guid\n" +
                        "  Left Join Wo3_Frame_Map Fm\n" +
                        "    On Fm.Map_Id = Obj.Map_Id\n" +
                        "  left join workorderstep3 w1\n" +
                        "    on Obj.OBJECTIVE_GUID=w1.WORKORDER_GUID\n" +
                        "  left join wo3_node_map wn\n" +
                        "    on wn.MAP_ID=Obj.MAP_ID\n" +
                        "  Left Join Wo3_Node_Map Nm\n" +
                        "    On Obj.Curstep_Id_Map = Nm.Nodemap_Id\n" +
                        "   And Nm.Map_Id = Fm.Map_Id\n" +
                        "  Left Join Customer Cus\n" +
                        "    On Obj.Customer_Guid = Cus.Customer_Guid\n" +
                        "  Left Join Sysc_Priority Priy\n" +
                        "    On Eta.Priority = Priy.Priority_Id\n" +
                        "  Left Join Rolegroup R1\n" +
                        "    On R1.Rolegroup_Id = Obj.Handlegroup_Id\n" +
                        "  Left Join Staff S1\n" +
                        "    On S1.Staff_Id = Obj.Handleby_Id\n" +
                        "  Left Join Staff S2\n" +
                        "    On S2.Staff_Id = Obj.Modifiedby\n" +
                        "  Left Join sysc_objectivestatus so\n" +
                        "    On obj.objectivestatus = so.objectivestatus\n" +
                        "  Left Join tabcwo_business_info tw\n" +
                        "    On tw.RELATION_ID = obj.OBJECTIVE_GUID\n" +
                        "  Left Join role role\n" +
                        "    On role.role_id = obj.handlerole_id\n" +
                        "  Left Join Staffrolegroup Sr\n" +
                        "    On Sr.Staff_Id = S1.Staff_Id\n" +
                        "  Left Join staff sct\n" +
                        "    On sct.Staff_Id = Obj.CREATEDBY\n" +
                        "  Where Fm.Category <> 'SALE01' and fm.Map_id<>'8IAUGM'\n" + q_WhereSQL;

                log.debug("执行工单查询数据SQL:" + queryWorkOrderSQL);

                List WorkOrderList = eliteBean.chaxun_sql(queryWorkOrderSQL, "dataSource");
                //获取总行数
                log.debug("执行工单查询数据SQL获取总条数:" + WorkOrderList.size());

                String reJoson = Util.getJsonFromList(WorkOrderList);
                reJoson=!KHUtil.isNull(reJoson)?reJoson:"[]";
                long endTime = System.currentTimeMillis();
                result.put("code", 1);
                result.put("msg", "处理完成、调用问题处理时长(毫秒):" + (endTime - startTime));
                JSONArray dataArr = JSONArray.parseArray(reJoson);
                result.put("data", dataArr);

            } catch (Exception e) {
                result.put("code", 1008);
                result.put("msg", e.getMessage());
            }

        }

        return result.toString();
    }
}